package com.base.log;

import com.base.exception.ModelAndViewRuntimeException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Objects;

@Component
@Aspect
@Order(1)
@Slf4j
public class LoginCheckAspect {

    private final RedisTemplate<String, Object> redisTemplate;

    private final HttpSession session;

    private final static String dir = "WEB_USER_INFO:";

    public LoginCheckAspect(RedisTemplate<String, Object> redisTemplate,
                            HttpSession session) {
        this.redisTemplate = redisTemplate;
        this.session = session;
    }

    @Around("@annotation(com.base.log.LoginAn) && @annotation(loginAn)")
    public Object loginCheckAspectAround(ProceedingJoinPoint point, LoginAn loginAn) throws Throwable {
        final String id = session.getId();
        Object o = redisTemplate.opsForValue().get(dir + id);
        if (Objects.isNull(o)) {
            session.setAttribute("adminUserId", null);
            redisTemplate.delete(id);
            if (!loginAn.isRe()) {
                return new ModelAndView("jsp/loginCheck1");
            } else {
                throw new ModelAndViewRuntimeException("redirect:/admin/loginCheck1");
            }

        }
        return point.proceed(point.getArgs());
    }
}
